import React, { useEffect, useState, useCallback, useRef, useMemo, act } from 'react'
import { Action } from 'redux';
import { bem, genUUID, isEmpty } from '@/utils';
import './shopingcart.scss';
import { CartGroupType, ActItemType, UpdateCartActionType } from './typing';
import checkIcon from '@/assets/check.png';
import checkedIcon from '@/assets/checkbox_checked.png';
import Loadding from '@/components/loadding';
import CartItem from './Cart/CartItem';
import NavBar from '@/components/navbar/navbar';
import Price from '@/components/price';
import classNames from 'classnames';
import { useAppSelector, useAppDispatch } from '@/store';
import {
    updateCartList,
    checkItem,
    checkShopAll,
    checkAll,
    updateQuantity,
    deleteSelectedCart,
    findActItem,

} from '@/store/reducers/cartReducersV2';
import { useNavigate } from 'react-router-dom';
import Btn from '@/components/button';

export interface ShoppingCartProps {
    cartList?: Array<CartGroupType>;
    isCache: boolean;
    manageOpen?: boolean;

}

const defaultProps = {
    cartList: [
        {
            checkType: false,
            shopId: 1,
            shopInfo: {
                shopId: 1,
                shopName: 'NICK旗舰店'
            },
            actItems: [{
                actId: 1,
                actName: '满减活动',
                actDesc: '满100减10',
                checkType: false,
                carts: [
                    {
                        checkType: false,
                        cartId: 1,
                        goodsId: 1,
                        goodsName: '耐克女子宽松防晒长裤透气中腰梭织拼接网眼运动裤NIKE FV7661 010黑/白 XL',
                        goodsImg: 'https://img10.360buyimg.com/mobilecms/s234x234_jfs/t1/331372/26/26405/50712/68fb9caeFe59ea75b/4a197b655c6a31fa.jpg!q70.dpg.webp',
                        goodsPrice: 10,
                        quantity: 1,
                        skuLabels: [
                            {
                                desc: '7天价保'
                            },
                            {
                                desc: '百亿补贴'
                            }
                        ],
                        mainSku: {
                            skuId: 1,
                            skuName: '商品1-sku1',
                            skuPrice: 10,
                            skuSpecsDesc: '010黑/白，XS'
                        }
                    },
                    {
                        checkType: false,
                        cartId: 3,
                        goodsId: 1,
                        goodsName: '耐克女子宽松防晒长裤透气中腰梭织拼接网眼运动裤NIKE FV7661 010黑/白 XL',
                        goodsImg: 'https://img10.360buyimg.com/mobilecms/s234x234_jfs/t1/331372/26/26405/50712/68fb9caeFe59ea75b/4a197b655c6a31fa.jpg!q70.dpg.webp',
                        goodsPrice: 10,
                        quantity: 1,
                        skuLabels: [
                            {
                                desc: '7天价保'
                            },
                            {
                                desc: '百亿补贴'
                            }
                        ],
                        mainSku: {
                            skuId: 3,
                            skuName: '商品1-sku1',
                            skuPrice: 10,
                            skuSpecsDesc: '010黑/白，XS'
                        }
                    }
                ]
            }]
        },

        {
            checkType: false,
            shopId: 2,
            shopInfo: {
                shopId: 2,
                shopName: 'NICK旗舰店2'
            },
            actItems: [{
                actId: 0,
                actName: '',
                actDesc: '',
                checkType: false,
                carts: [
                    {
                        checkType: false,
                        cartId: 4,
                        goodsId: 4,
                        goodsName: '耐克女子宽松防晒长裤透气中腰梭织拼接网眼运动裤NIKE FV7661 010黑/白 XL',
                        goodsImg: 'https://img10.360buyimg.com/mobilecms/s234x234_jfs/t1/331372/26/26405/50712/68fb9caeFe59ea75b/4a197b655c6a31fa.jpg!q70.dpg.webp',
                        goodsPrice: 10,
                        quantity: 1,
                        skuLabels: [
                            {
                                desc: '7天价保'
                            },
                            {
                                desc: '百亿补贴'
                            }
                        ],
                        mainSku: {
                            skuId: 4,
                            skuName: '商品1-sku1',
                            skuPrice: 10,
                            skuSpecsDesc: '010黑/白，XS'
                        }
                    },
                    {
                        checkType: false,
                        cartId: 5,
                        goodsId: 5,
                        goodsName: '耐克女子宽松防晒长裤透气中腰梭织拼接网眼运动裤NIKE FV7661 010黑/白 XL',
                        goodsImg: 'https://img10.360buyimg.com/mobilecms/s234x234_jfs/t1/331372/26/26405/50712/68fb9caeFe59ea75b/4a197b655c6a31fa.jpg!q70.dpg.webp',
                        goodsPrice: 10,
                        quantity: 1,
                        skuLabels: [
                            {
                                desc: '7天价保'
                            },
                            {
                                desc: '百亿补贴'
                            }
                        ],
                        mainSku: {
                            skuId: 5,
                            skuName: '商品1-sku1',
                            skuPrice: 10,
                            skuSpecsDesc: '010黑/白，XS'
                        }
                    }
                ]
            }]
        }
    ]
};

const ShoppingCart: React.FC<ShoppingCartProps> = (props) => {
    const {
        cartList,
        ...rest
    } = {
        ...defaultProps,
        ...props
    };
    const b = bem('shoppingCart');

    const navigate = useNavigate();

    const [isLoading, setIsLoading] = useState(false);

    const dispatch = useAppDispatch();
    const cartState = useAppSelector(state => state.cartV2);
    const { shopItemIndex, actItemIndex, cartItemIndex } = cartState;

    // 全选中购物车商品数据
    const [checkAllState, setCheckAllState] = useState(false);
    const [manageOpen, setManageOpen] = useState(false);


    console.log('cartState', cartState);

    const actionHandler = (action: Action) => {
        setIsLoading(true);

        dispatch(action);

        setIsLoading(false);
    };

    useEffect(() => {
        actionHandler(updateCartList(cartList));
    }, []);


    const checkSelectAll = useCallback(() => {
        const checked = !checkAllState;

        // 全选所有商品
        actionHandler(checkAll({ checkType: checked }));

        setCheckAllState(checked);
    }, [checkAllState]);

    /**
     * 全选/取消全选店铺商品
     */
    const handleShopCheckAll = (shopId: string | number) => {
        actionHandler(checkShopAll({ shopId }));
    };

    // 单选
    const handlerCheckItem = (value: UpdateCartActionType) => {
        if (!value) {
            return;
        }
        actionHandler(checkItem(value));
    }

    /**
     * 全选/取消全选店铺商品
     */
    const handlerQuantity = useCallback((value: UpdateCartActionType) => {
        if (!value) {
            return;
        }
        actionHandler(updateQuantity(value));
    }, []);

    const handlerOpenManage = () => {
        setManageOpen(!manageOpen);
    }

    const handlerSelectDelete = () => {
        actionHandler(deleteSelectedCart({}));
    }

    const handlerGoodsClick = (value: any) => {
        const { goodsId } = value;
        if (!goodsId) {
            return;
        }
        // 跳转商品详情
        navigate('/goods/detail/' + goodsId);
    }

    const handlerConfirmOrder = () => {

        console.log('去结算', cartState.selectedCart);
        // navigate('/order/confirm');
    }

    const renderShopCart = useMemo(() => {
        return Object.keys(shopItemIndex).map((key) => {
            const shopId = key;
            const { checkType, shopInfo, actIds } = shopItemIndex[key];

            return (
                <div className={b('section')} key={shopId} >
                    {
                        <div className={b('section-head')}>
                            <div className={b('icon-select')} onClick={() => handleShopCheckAll(shopId)}>
                                <img className={b('icon-select__check')} src={checkType ? checkedIcon : checkIcon} />
                            </div>
                            <div className={b('section-title')}>
                                <div className={b('section-title__name')}>{shopInfo?.shopName}</div>
                            </div>
                        </div>
                    }
                    {
                        actIds?.map((actId) => {
                            const actItem = findActItem(actItemIndex, {
                                shopId, actId
                            });
                            if (!actItem) {
                                return;
                            }
                            const { cartIds } = actItem;

                            return cartIds && cartIds?.map((cartId) => {
                                const cartItem = cartItemIndex[cartId];
                                if (!cartItem) {
                                    return;
                                }
                                return <CartItem
                                    key={cartId}
                                    actId={actId}
                                    shopId={shopId}
                                    cartItem={cartItem}
                                    onHandlerSelect={handlerCheckItem}
                                    onHandlerQuantity={handlerQuantity}
                                    onHandlerClick={handlerGoodsClick}
                                />
                            })
                        })
                    }
                </div>
            )

        })
    }, [shopItemIndex, actItemIndex, cartItemIndex, handleShopCheckAll, handlerCheckItem, handlerQuantity, handlerGoodsClick]);


    if (isLoading) {
        return <Loadding visible type="loading" />;
    }

    return (
        <>
            <div className={b('head')}>
                <NavBar
                    backIcon={true}
                    content={'购物车'}
                    search={false}
                />

                <div className={b('address-bar-wrap')}>

                    <div className={b('address-bar')}>
                        <div className={b('address')}>
                            <div>朝阳区三环到四环之间</div>
                        </div>
                        <div className={b('btn')} onClick={handlerOpenManage}>
                            {
                                manageOpen ? '取消' : '管理'
                            }
                        </div>
                    </div>

                </div>
            </div>
            <div className={b('section-list')}>
                {
                    renderShopCart
                }
            </div>

            <Loadding visible type='noMore' />
            <div className={b('fixBar')}>
                <div className={b('bar')}>
                    <div className={b('bar-select')} onClick={() => checkSelectAll()}>
                        <img className={b('icon-select__check')} src={checkAllState ? checkedIcon : checkIcon} />
                        <span className={b('bar-select-all')}>全选</span>
                    </div>

                    <div className={b('content')}>
                        {
                            manageOpen ? (
                                <div className={b('manage')}>
                                    <div className={classNames(b('manage-btn'), b('manage-btn-delete'))} onClick={handlerSelectDelete}>删除</div>
                                    <div className={classNames(b('manage-btn'), b('manage-btn-fac'))}>收藏</div>
                                </div>
                            ) : (
                                <div className={b('total')} >
                                    <div className={b('total-detail')}>
                                        <div className={b('total-count')}>
                                            合计:
                                        </div>
                                        <Price price={10234} />
                                    </div>
                                    <Btn btnTitle="去结算" onClick={handlerConfirmOrder} />
                                </div>
                            )
                        }
                    </div>
                </div>
            </div>


        </>
    )
};

export default ShoppingCart;